﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using DukeNUS.FacilitiesPlanning.FPSystem.Data;
using DukeNUS.FacilitiesPlanning.FPSystem.Models;
using System.Diagnostics;

namespace DukeNUS.FacilitiesPlanning.FPSystem.Data.Defaults
{

    public class DefaultUsers: IDefaultData
    {

        public void Create()
        {
            try
            {
                using (DukeNUSDatabase db = new DukeNUSDatabase())
                {
                    if (!db.Users.Any())
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            string path = ConfigurationManager.AppSettings["DefaultUsers"];
                            XElement xml = XElement.Load(HttpContext.Current.Server.MapPath(path));

                            var query = from defaultUsers in xml.Elements("defaultuser")
                                        select defaultUsers;

                            foreach (var defaultUser in query)
                            {
                                var username = (string)defaultUser.Element("username");
                                var isadminvalue = (string)defaultUser.Element("isadmin");
                                var isadmin = (isadminvalue.ToLower() == "true" ||
                                               isadminvalue.ToLower() == "1");

                                if (!db.Users.Any(u => (u.UserName == username)))
                                     db.Users.Add(new User()
                                    {
                                        UserName = username,
                                        DecryptedPassword = (string)defaultUser.Element("password"),
                                        FullName = (string)defaultUser.Element("fullname"),
                                        Designation = (string)defaultUser.Element("designation"),
                                        Department = (string)defaultUser.Element("department"),
                                        Email = (string)defaultUser.Element("email"),
                                        IsAdmin = isadmin
                                    });
                            }

                            db.SaveChanges(); trans.Complete();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(GetType().FullName, string.Format("Message: {0}\nStack Trace: {1}", ex.Message, ex.StackTrace), EventLogEntryType.Error);
            } 
        }

    }

}